// 获取指定商品的评论
async function getProductComments(productId) {
    try {
        console.log('正在获取商品评论，商品ID:', productId);
        const response = await fetch(`/api/comments?productId=${productId}`);
        
        if (!response.ok) {
            const errorText = await response.text();
            console.error('服务器响应错误:', response.status, errorText);
            throw new Error(`获取评论失败: ${response.status}`);
        }

        const comments = await response.json();
        console.log('获取到的评论:', comments);
        return comments;
    } catch (error) {
        console.error('获取评论错误:', error);
        throw error; // 让上层处理错误
    }
}

// 添加新评论
async function addComment(productId, content, rating) {
    console.log('开始提交评论:', { productId, content, rating });
    
    const currentUser = getCurrentUser();
    if (!currentUser) {
        console.log('用户未登录');
        alert('请先登录');
        return false;
    }

    try {
        const commentData = {
            productId: productId,
            userId: currentUser.username,
            content: content,
            rating: rating
        };
        
        console.log('发送评论数据:', commentData);

        const response = await fetch('/api/comments', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(commentData)
        });

        console.log('服务器响应状态:', response.status);

        if (!response.ok) {
            const errorText = await response.text();
            console.error('服务器返回错误:', errorText);
            throw new Error(`提交评论失败: ${response.status} ${errorText}`);
        }

        const result = await response.json();
        console.log('评论提交结果:', result);

        if (result.status === 'success') {
            console.log('评论提交成功');
            return true;
        } else {
            console.error('评论提交失败:', result);
            throw new Error('服务器处理评论失败');
        }
    } catch (error) {
        console.error('提交评论时发生错误:', error);
        throw error;
    }
}

// 格式化日期
function formatDate(dateString) {
    const options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' };
    return new Date(dateString).toLocaleDateString('zh-CN', options);
}

// 渲染评分星星
function renderStars(rating) {
    const fullStar = '★';
    const emptyStar = '☆';
    return (fullStar.repeat(rating) + emptyStar.repeat(5 - rating));
}

// 渲染评论列表
async function renderComments(productId) {
    console.log('开始渲染评论，商品ID:', productId);
    
    const commentsContainer = document.getElementById('commentsList');
    if (!commentsContainer) {
        console.error('找不到评论容器元素');
        return;
    }

    commentsContainer.innerHTML = '<p class="loading">加载评论中...</p>';
    
    try {
        console.log('正在获取评论数据...');
        const comments = await getProductComments(productId);
        console.log('获取到评论数据:', comments);
        
        if (!Array.isArray(comments)) {
            console.error('评论数据格式错误:', comments);
            throw new Error('评论数据格式错误');
        }
        
        if (comments.length === 0) {
            console.log('没有找到评论');
            commentsContainer.innerHTML = '<p class="no-comments">暂无评论</p>';
            return;
        }

        console.log('开始生成评论HTML');
        const commentsHtml = comments.map(comment => {
            if (!comment.userId || !comment.content) {
                console.warn('评论数据不完整:', comment);
                return '';
            }
            return `
                <div class="comment">
                    <div class="comment-header">
                        <span class="comment-user">${comment.userId}</span>
                        <span class="comment-rating">${renderStars(comment.rating)}</span>
                    </div>
                    <div class="comment-content">${comment.content}</div>
                    <div class="comment-footer">
                        <span class="comment-date">${formatDate(comment.createdAt)}</span>
                    </div>
                </div>
            `;
        }).join('');

        console.log('渲染评论HTML');
        commentsContainer.innerHTML = commentsHtml;
        console.log('评论渲染完成');
    } catch (error) {
        console.error('渲染评论时发生错误:', error);
        commentsContainer.innerHTML = `
            <div class="error">
                <p>加载评论失败: ${error.message}</p>
                <button onclick="retryLoadComments(${productId})" class="retry-button">
                    重试
                </button>
            </div>
        `;
    }
}

// 处理评论提交
async function handleCommentSubmit(event) {
    event.preventDefault();
    
    const productId = parseInt(getUrlParam('id'));
    const content = document.getElementById('commentContent').value.trim();
    const rating = parseInt(document.getElementById('rating').value);
    
    if (!content) {
        showSubmitFeedback('请输入评论内容', 'error');
        return;
    }

    const submitButton = event.target.querySelector('button[type="submit"]');
    submitButton.disabled = true;
    submitButton.textContent = '提交中...';

    try {
        if (await addComment(productId, content, rating)) {
            // 清空输入框
            document.getElementById('commentContent').value = '';
            document.getElementById('rating').value = '5';
            // 显示成功消息
            showSubmitFeedback('评论提交成功！');
            // 重新渲染评论列表
            await renderComments(productId);
        } else {
            showSubmitFeedback('评论提交失败，请重试', 'error');
        }
    } catch (error) {
        console.error('提交评论出错:', error);
        showSubmitFeedback('评论提交时发生错误，请重试', 'error');
    } finally {
        submitButton.disabled = false;
        submitButton.textContent = '提交评价';
    }
}

// 初始化评论功能
async function initComments() {
    const productId = parseInt(getUrlParam('id'));
    if (!productId) return;

    // 渲染评论列表
    await renderComments(productId);

    // 绑定评论表单提交事件
    const commentForm = document.getElementById('commentForm');
    if (commentForm) {
        commentForm.addEventListener('submit', handleCommentSubmit);
    }

    // 添加错误处理的全局事件监听器
    window.addEventListener('unhandledrejection', function(event) {
        console.error('评论系统错误:', event.reason);
        const commentsContainer = document.getElementById('commentsList');
        if (commentsContainer) {
            commentsContainer.innerHTML = `
                <div class="error">
                    <p>加载评论时出现错误</p>
                    <button onclick="retryLoadComments(${productId})" class="retry-button">
                        重试
                    </button>
                </div>
            `;
        }
    });
}

// 重试加载评论
async function retryLoadComments(productId) {
    try {
        await renderComments(productId);
    } catch (error) {
        console.error('重试加载评论失败:', error);
    }
}

// 显示提交反馈
function showSubmitFeedback(message, type = 'success') {
    const feedbackDiv = document.createElement('div');
    feedbackDiv.className = `submit-feedback ${type}`;
    feedbackDiv.textContent = message;
    
    const form = document.getElementById('commentForm');
    form.appendChild(feedbackDiv);
    
    setTimeout(() => {
        feedbackDiv.remove();
    }, 3000);
}

// 页面加载完成后初始化评论功能
document.addEventListener('DOMContentLoaded', () => {
    if (checkAuth()) {
        initComments();
    }
});